package cn.edu.niit.servlet;

import cn.edu.niit.dao.AdminDao;
import cn.edu.niit.javabean.Message;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/message")
public class AdminMessageServlet extends HttpServlet {
    AdminDao adminDao = new AdminDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, String[]> parameterMap = req.getParameterMap();
        if (parameterMap != null) {
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                params.put(entry.getKey(), entry.getValue()[0]);
            }
        }
        int pageNum = Integer.parseInt((String) params.get("pageNum"));
        int pageSize =Integer.parseInt((String) params.get("pageSize"));
        String username= (String) params.get("username");
        List<Message> messages = adminDao.getAllMessage(username, pageNum, pageSize);
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> subMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("msg", "");
        subMap.put("count", adminDao.getAllMessageCount(username));
        subMap.put("list", messages);
        resultMap.put("data", subMap);
        resultMap.put("errorNo", "0");
        resp.getWriter().print(JSONObject.toJSONString(resultMap));

    }
}
